<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <title>share paper</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <!-- 新 Bootstrap 核心 CSS 文件 -->
  <!-- <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> -->
  <!--        <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>-->
  <style>
    fieldset {
      display: block;
      margin-inline-start: 2px;
      margin-inline-end: 2px;
      padding-block-start: 0.35em;
      padding-inline-start: 0.75em;
      padding-inline-end: 0.75em;
      padding-block-end: 0.625em;
      min-inline-size: min-content;
      border-width: 2px;
      border-style: groove;
      border-color: threedface;
      border-image: initial;
    }

    legend {
      display: block;
      padding-inline-start: 2px;
      padding-inline-end: 2px;
      border-width: initial;
      border-style: none;
      border-color: initial;
      border-image: initial;
    }

    input {
      color: #fff;
      background-color: #409eff;
      border-color: #409eff;
      padding: 10px 15px;
      font-size: 18px;
      border-radius: 4px;
    }

    textarea {
      padding: 8px 8px;
    }
  </style>
</head>

<body>
  <fieldset>
    <legend><b>
        <a href="https://gitee.com/soekchl/sharePaper" title="Share Paper">
          <img width="20" title="Share Paper" src="https://github.com/fluidicon.png"></a>
        共享记事本</b> <label for="" id="online">online </label></legend>
    <input type="button" id="add" value="Add"></input><br>
    <div id="texts">
    </div>
  </fieldset>
</body>

</html>
<script>
  add.onclick = addText
  let ws = null
  let textCount = 1
  let initFlag = true
  addText(0)
  conn()

  function addText(count, value = '', lockFlag = false) {
    if (typeof count === 'object') {
      count = textCount++
    } else if (textCount <= count) {
      textCount = count + 1
    }
    console.log('add', count)
    let tmp = document.createElement('textarea')
    tmp.id = `memory_${count}`
    tmp.name = count
    tmp.style = "width:45%; height: 100px; resize: none;"
    tmp.oninput = changeText
    tmp.placeholder = `share paper memory ${count}`
    tmp.onkeyup = checkDel
    tmp.disabled = lockFlag
    tmp.onfocus = lock
    tmp.onblur = unlock
    // tmp.onmouseover = console.log
    tmp.value = value
    texts.appendChild(tmp)
    // texts.children[texts.children.length - 1].focus()
  }
  function lock(e) {
    if (initFlag) {
      return
    }
    console.log(e.target.id, 'lock')
    // e.target.disabled = true
    sendData(4, e.target.name)
  }

  function unlock(e) {
    if (initFlag) {
      return
    }
    console.log(e.target.id, 'unlock')
    sendData(5, e.target.name)
  }

  function checkDel() {
    let x;
    if (window.event) // IE8 以及更早版本
    {
      x = event.keyCode;
    }
    else if (event.which) // IE9/Firefox/Chrome/Opera/Safari
    {
      x = event.which;
    }
    if (x === 8 && this.value.length < 1) {
      this.remove()
    }
  }

  function conn() {
    if (ws) {
      return
    }
    initFlag = true
     let wsUrl = "ws://192.168.2.248:8080/webSocket";
    //let wsUrl = "wss://share.utcgame.com/webSocket";
    ws = new WebSocket(wsUrl);
    try {
      ws.onopen = function () {
        console.log("open")
      }
      ws.onclose = function () {
        if (ws) {
          ws.close();
          ws = null;
        }
        console.log("close ws")
        checkReConn()
      }
      ws.onmessage = function (result) {
        var data = JSON.parse(result.data);
        console.log(data)
        switch (data.cmd) {
          case 1: initData(data); break;
          case 2: editMemory(data); break
          case 3: online.innerText = `在线人数：${data.data}`; break
          case 4: setMemoryStatus(data.index, true); break;
          case 5: setMemoryStatus(data.index, false); break;
        }
      }
    } catch (e) {
      console.log(e.message);
    }
  }

  function setMemoryStatus(index, lockFlag = true) {
    let tmp = document.getElementById(`memory_${index || 0}`)
    if (tmp) {
      console.log(index, 'lock')
      tmp.disabled = lockFlag
    }
  }

  function editMemory(data) {
    let tmp = document.getElementById(`memory_${data.index || 0}`)
    if (tmp) {
      tmp.value = data.data
      tmp.disabled = true
    } else {
      addText(data.index, data.data, true)
    }
    // tmp.focus()
  }

  function initData(data) {
    let list = JSON.parse(data.data)
    // console.log(list)
    for (let key in list) {
      const item = list[key]
      let tmp = document.getElementById(`memory_${key || 0}`)
      if (tmp) {
        tmp.value = item.data
        tmp.disabled = item.lock
      } else {
        addText(+key, item.data, item.lock)
      }
    }
    initFlag = false
  }

  function checkReConn() {
    if (ws) {
      return
    }
    if (confirm("连接已断开，是否重新连接？")) {
      conn()
    }
  }

  function sendData(cmd, index, data = '') {
    let tmpData = { cmd, index: +index, data }
    if (!ws) {
      return
    }
    ws.send(JSON.stringify(tmpData))
  }

  function changeText() {
    if (!ws) {
      console.log("closed ws")
      checkReConn()
      return
    }
    sendData(2, +this.name, this.value)
  }
</script>